var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

var phrases = ['yahooooo', 'gooogle', 'micosoft', 'no no no'];

app.set('view engine', 'jade');
app.set('view options', {layout: true});
app.set('views', __dirname + '/views');

app.get('/stooges/chat', function(req, res) {
	res.render('chat');
});

io.sockets.on('connection', function(socket) {
	var sendChat = function(title, text) {
		socket.emit('chat', {
			title: title,
			content: text
		});
	};

	/*setInterval(function() {
		var randomIndex = Math.floor(Math.random() * phrases.length);
		sendChat('Stooges Title', phrases[randomIndex]);
	}, 5000);*/

	sendChat('Welcome to stooges chat', 'We are on the line');

	socket.on('chat', function(data) {
		sendChat('Anonymous', data.text);
	});

});

app.get('/stooges/:name?', function(req, res, next) {
	var name = req.params.name;

	switch(name ? name.toLowerCase() : '') {
		case 'an':
		case 'steve':
		case 'joseph':
			res.render('stooges', {stooge: name});
			break;

		default:
			next();
	}
});

app.get('/stooges/*?', function(req, res) {
	res.render('stooges', {stooge: null});
});

app.get('/?', function(req, res) {
	res.render('index');
})

server.listen(9241);
console.log('listening.....');